/**
 * 抽奖管理器
 * 负责管理抽奖逻辑、概率计算、中奖记录和抽奖券管理
 */

class LotteryManager {
  constructor() {
    this.storageKeys = {
      WINNING_RECORDS: 'lottery_winning_records',
      LOTTERY_TICKETS: 'lottery_tickets_count'
    }
    this.maxRecords = 20 // 最多保存20条记录
  }

  /**
   * 执行抽奖逻辑（基于概率随机选择奖品）
   * @param {Array} prizes - 奖品数组，每个奖品包含 probability 字段
   * @returns {Object} 中奖的奖品对象
   */
  draw(prizes) {
    if (!prizes || prizes.length === 0) {
      throw new Error('奖品列表不能为空')
    }

    // 验证概率总和
    const totalProbability = prizes.reduce((sum, prize) => sum + (prize.probability || 0), 0)
    if (Math.abs(totalProbability - 100) > 0.01) {
      console.warn('奖品概率总和不等于100%:', totalProbability)
    }

    // 生成随机数 (0-100)
    const random = Math.random() * 100
    
    // 根据概率区间选择奖品
    let cumulativeProbability = 0
    for (let i = 0; i < prizes.length; i++) {
      cumulativeProbability += prizes[i].probability || 0
      if (random <= cumulativeProbability) {
        return prizes[i]
      }
    }

    // 如果没有选中（理论上不应该发生），返回最后一个奖品
    return prizes[prizes.length - 1]
  }

  /**
   * 计算概率区间（用于验证和调试）
   * @param {Array} prizes - 奖品数组
   * @returns {Array} 概率区间数组
   */
  calculateProbability(prizes) {
    const intervals = []
    let cumulative = 0

    prizes.forEach(prize => {
      const start = cumulative
      const end = cumulative + (prize.probability || 0)
      intervals.push({
        prize: prize.name,
        probability: prize.probability,
        range: [start, end]
      })
      cumulative = end
    })

    return {
      intervals,
      total: cumulative,
      isValid: Math.abs(cumulative - 100) < 0.01
    }
  }

  /**
   * 验证抽奖资格
   * @param {String} type - 抽奖类型：'points' 或 'ticket'
   * @param {Number} userPoints - 用户当前积分
   * @param {Number} ticketCount - 用户当前抽奖券数量
   * @param {Number} pointsCost - 积分抽奖消耗
   * @param {Number} ticketCost - 抽奖券消耗
   * @returns {Object} { canDraw: Boolean, reason: String }
   */
  canDraw(type, userPoints, ticketCount, pointsCost = 50, ticketCost = 1) {
    if (type === 'points') {
      if (userPoints < pointsCost) {
        return {
          canDraw: false,
          reason: '积分不足，请前往完成任务获取积分'
        }
      }
    } else if (type === 'ticket') {
      if (ticketCount < ticketCost) {
        return {
          canDraw: false,
          reason: '抽奖券不足，请前往商城购买'
        }
      }
    } else {
      return {
        canDraw: false,
        reason: '无效的抽奖类型'
      }
    }

    return {
      canDraw: true,
      reason: ''
    }
  }

  /**
   * 保存中奖记录
   * @param {Object} record - 中奖记录对象
   * @returns {Boolean} 是否保存成功
   */
  saveWinningRecord(record) {
    try {
      const records = this.getWinningRecords()
      
      // 添加新记录到开头
      const newRecord = {
        id: Date.now(),
        prizeName: record.prizeName,
        prizeIcon: record.prizeIcon,
        prizeType: record.prizeType,
        costType: record.costType, // 'points' | 'ticket'
        costAmount: record.costAmount,
        timestamp: Date.now(),
        dateText: this.formatDate(new Date())
      }
      
      records.unshift(newRecord)
      
      // 限制最多保存20条记录
      if (records.length > this.maxRecords) {
        records.splice(this.maxRecords)
      }
      
      uni.setStorageSync(this.storageKeys.WINNING_RECORDS, JSON.stringify(records))
      return true
    } catch (error) {
      console.error('保存中奖记录失败:', error)
      return false
    }
  }

  /**
   * 获取中奖记录
   * @returns {Array} 中奖记录数组
   */
  getWinningRecords() {
    try {
      const recordsStr = uni.getStorageSync(this.storageKeys.WINNING_RECORDS)
      if (!recordsStr) {
        return []
      }
      return JSON.parse(recordsStr)
    } catch (error) {
      console.error('获取中奖记录失败:', error)
      return []
    }
  }

  /**
   * 清空中奖记录
   * @returns {Boolean} 是否清空成功
   */
  clearWinningRecords() {
    try {
      uni.removeStorageSync(this.storageKeys.WINNING_RECORDS)
      return true
    } catch (error) {
      console.error('清空中奖记录失败:', error)
      return false
    }
  }

  /**
   * 获取抽奖券数量
   * @returns {Number} 抽奖券数量
   */
  getLotteryTickets() {
    try {
      const count = uni.getStorageSync(this.storageKeys.LOTTERY_TICKETS)
      return count ? parseInt(count) : 0
    } catch (error) {
      console.error('获取抽奖券数量失败:', error)
      return 0
    }
  }

  /**
   * 设置抽奖券数量
   * @param {Number} count - 抽奖券数量
   * @returns {Boolean} 是否设置成功
   */
  setLotteryTickets(count) {
    try {
      uni.setStorageSync(this.storageKeys.LOTTERY_TICKETS, count)
      return true
    } catch (error) {
      console.error('设置抽奖券数量失败:', error)
      return false
    }
  }

  /**
   * 增加抽奖券
   * @param {Number} count - 增加的数量
   * @returns {Boolean} 是否增加成功
   */
  addLotteryTickets(count) {
    try {
      const currentCount = this.getLotteryTickets()
      const newCount = currentCount + count
      return this.setLotteryTickets(newCount)
    } catch (error) {
      console.error('增加抽奖券失败:', error)
      return false
    }
  }

  /**
   * 减少抽奖券
   * @param {Number} count - 减少的数量
   * @returns {Boolean} 是否减少成功
   */
  reduceLotteryTickets(count) {
    try {
      const currentCount = this.getLotteryTickets()
      if (currentCount < count) {
        console.warn('抽奖券数量不足')
        return false
      }
      const newCount = currentCount - count
      return this.setLotteryTickets(newCount)
    } catch (error) {
      console.error('减少抽奖券失败:', error)
      return false
    }
  }

  /**
   * 格式化日期
   * @param {Date} date - 日期对象
   * @returns {String} 格式化后的日期字符串
   */
  formatDate(date) {
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
  }

  /**
   * 获取相对时间描述
   * @param {Number} timestamp - 时间戳
   * @returns {String} 相对时间描述
   */
  getRelativeTime(timestamp) {
    const now = Date.now()
    const diff = now - timestamp
    
    const seconds = Math.floor(diff / 1000)
    const minutes = Math.floor(seconds / 60)
    const hours = Math.floor(minutes / 60)
    const days = Math.floor(hours / 24)
    
    if (seconds < 60) {
      return '刚刚'
    } else if (minutes < 60) {
      return `${minutes}分钟前`
    } else if (hours < 24) {
      return `${hours}小时前`
    } else if (days < 7) {
      return `${days}天前`
    } else {
      return this.formatDate(new Date(timestamp))
    }
  }

  /**
   * 初始化测试数据（用于开发测试）
   */
  initTestData() {
    // 设置初始抽奖券数量
    this.setLotteryTickets(5)
    
    // 添加一些测试记录
    const testRecords = [
      {
        prizeName: '传说级武器',
        prizeIcon: '⚔️',
        prizeType: 'weapon',
        costType: 'points',
        costAmount: 50
      },
      {
        prizeName: '史诗皮肤',
        prizeIcon: '🎨',
        prizeType: 'skin',
        costType: 'ticket',
        costAmount: 1
      },
      {
        prizeName: '积分奖励',
        prizeIcon: '💰',
        prizeType: 'points',
        costType: 'points',
        costAmount: 50
      }
    ]
    
    testRecords.forEach(record => {
      this.saveWinningRecord(record)
    })
    
    console.log('抽奖测试数据初始化完成')
  }
}

// 创建单例实例
const lotteryManager = new LotteryManager()

export default lotteryManager
